//
//  DestinationViewController.m
//  HappinessTrip
//
//  Created by dllo on 15/9/30.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "DestinationViewController.h"
#import "GetDataMethods.h"
#import "RecommendData.h"
#import "PlaceCollectionViewCell.h"
#import "TitleCollectionReusableView.h"
#import "SearchCollectionViewCell.h"
#import "SearchElements.h"
#import "Model.h"
#import "Fit.h"
#import "MBProgressHUD.h"

#import "RecommendViewController.h"
#import "OtherViewController.h"
#import "SearchViewController.h"

@interface DestinationViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate>
@property(nonatomic, retain)UICollectionView *collectionView;
@property(nonatomic, retain)UICollectionView *searchCollectionView;
@property(nonatomic, retain)NSMutableArray *dataArray;
@property(nonatomic, retain)NSMutableArray *titleArray;
@property(nonatomic, retain)UISearchBar *searchBar;
@property(nonatomic, retain)UIView *searchView;
@property(nonatomic, retain)UIButton *cancelButton;
@property(nonatomic, retain)UIButton *searchButton;
@property(nonatomic, retain)NSMutableArray *searchArray;
@property(nonatomic, retain)NSMutableArray *searchArr;
@property(nonatomic, assign)NSInteger flag;
@property(nonatomic, retain)NSString *urlString;
@property(nonatomic, retain)MBProgressHUD *progressView;

@end

@implementation DestinationViewController
-(void)dealloc
{
    [_collectionView release];
    [_dataArray release];
    [_titleArray release];
    [_searchBar release];
    [_searchView release];
    [_searchButton release];
    [_cancelButton release];
    [_searchArray release];
    [_searchArr release];
    [super dealloc];
}

-(void)changeColor{
    self.collectionView.backgroundColor = [Model shareInstance].BackgroundColor;
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[Model shareInstance].TitleColor, NSForegroundColorAttributeName, nil]];
    self.navigationController.navigationBar.barTintColor = [Model shareInstance].BackgroundColor;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    UIView *searchView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
    self.navigationItem.titleView = searchView;
    [searchView release];
    _searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(10 * W, 5, 260 * W, 30)];
    _searchBar.delegate = self;
    _searchBar.placeholder = @"搜索国家、城市、景区、游览胜地";
    _searchBar.layer.cornerRadius = 5;
    _searchBar.layer.masksToBounds = YES;
    _searchBar.backgroundColor = [UIColor clearColor];
    [searchView addSubview:_searchBar];
    [_searchBar release];
    
    _searchButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _searchButton.frame = CGRectMake(_searchBar.frame.origin.x + _searchBar.frame.size.width + 10 * W, _searchBar.frame.origin.y, 40 * W, _searchBar.frame.size.height);
    [_searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [_searchButton addTarget:self action:@selector(searchButtonAction) forControlEvents:UIControlEventTouchUpInside];
    _searchButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [_searchButton setTitleColor:[UIColor colorWithRed:0.56 green:0.53 blue:0.93 alpha:1] forState:UIControlStateNormal];
    [searchView addSubview:_searchButton];
    
    _cancelButton = [UIButton buttonWithType:UIButtonTypeSystem];
    _cancelButton.frame = CGRectMake(_searchBar.frame.origin.x + _searchBar.frame.size.width + _searchButton.frame.size.width + 5 * W, _searchBar.frame.origin.y, _searchButton.frame.size.width, _searchButton.frame.size.height);
    [_cancelButton setTitle:@"取消" forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(cancelButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [_cancelButton setHidden:YES];
    _cancelButton.titleLabel.font = [UIFont systemFontOfSize:16];
    [_cancelButton setTitleColor:[UIColor colorWithRed:0.56 green:0.53 blue:0.93 alpha:1] forState:UIControlStateNormal];
    [searchView addSubview:_cancelButton];

    //上部推出页面
    _searchView = [[UIView alloc]initWithFrame:CGRectMake(0, - self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height - 64)];
    _flag = 0;
    _searchView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_searchView];
    [_searchView release];
    [self changeColor];

}
-(void)getData
{
    self.dataArray = [NSMutableArray array];
    self.titleArray = [NSMutableArray array];
    self.searchArray = [NSMutableArray array];
    self.searchArr = [NSMutableArray array];
    [GetDataMethods getDataByString:[NSString stringWithFormat:@"http://api.breadtrip.com/destination/v3/"] BodyString:nil WithDataBlock:^(id data) {
        
        NSArray *searchArray = [data objectForKey:@"search_data"];
        for (NSDictionary *searchDic in searchArray) {
            NSArray *elementsArray = [searchDic objectForKey:@"elements"];
            NSMutableArray *array = [NSMutableArray array];
            for (NSDictionary *elementsDic in elementsArray) {
                SearchElements *search = [[SearchElements alloc]init];
                [search setValuesForKeysWithDictionary:elementsDic];
                [array addObject:search];
            }
            [_searchArr addObject:[searchDic objectForKey:@"title"]];
            [_searchArray addObject:array];
        }
        NSArray *eleArray = [data objectForKey:@"elements"];
        for (NSDictionary *eleDic in eleArray) {
            [_titleArray addObject:[eleDic objectForKey:@"title"]];//存放标题
            NSMutableArray *dataArray = [eleDic objectForKey:@"data"];
            NSMutableArray *modelArray = [NSMutableArray array];
            for (NSDictionary *dataDic in dataArray) {
                RecommendData *data = [[RecommendData alloc]init];
                [data setValuesForKeysWithDictionary:dataDic];
                [modelArray addObject:data];
            }
            [_dataArray addObject:modelArray];//存放model数组,model数组里是data对象
        }
        [_collectionView reloadData];
        [self createViews];
        [_progressView removeFromSuperview];
    }];
}
-(void)createViews
{
    UICollectionViewFlowLayout *searchLayout = [[UICollectionViewFlowLayout alloc]init];
    searchLayout.itemSize = CGSizeMake(105 * W, 30 * H);
    searchLayout.minimumLineSpacing = 15 * W;
    searchLayout.minimumInteritemSpacing = 15 * H;
    searchLayout.sectionInset = UIEdgeInsetsMake(10 * W, 15 * H, 10 * W, 15 * H);
    searchLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _searchCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) collectionViewLayout:searchLayout];
    _searchCollectionView.dataSource = self;
    _searchCollectionView.delegate = self;
    _searchCollectionView.backgroundColor = [UIColor colorWithRed:1 green:0.95 blue:0.85 alpha:1];
    [_searchView addSubview:_searchCollectionView];
    [_searchCollectionView registerClass:[SearchCollectionViewCell class] forCellWithReuseIdentifier:@"identifier1"];
    [_searchCollectionView registerClass:[TitleCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head"];
    [_searchCollectionView release];
}

-(void)loadView
{
    [super loadView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor) name:@"changeColor" object:nil];
    [self getData];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(170 * W, 220 * H);
    flowLayout.minimumLineSpacing = 10 * H;
    flowLayout.minimumInteritemSpacing = 10 * W;
    flowLayout.sectionInset = UIEdgeInsetsMake(10 * W, 10 * H, 10 * W, 10 * H);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 113) collectionViewLayout:flowLayout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    [_collectionView registerClass:[PlaceCollectionViewCell class] forCellWithReuseIdentifier:@"identifier"];
    //添加页眉和页脚以前需要注册类和标识：
    [_collectionView registerClass:[TitleCollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.view addSubview:_collectionView];
    
    //加载视图初始化
    self.progressView = [[MBProgressHUD alloc]initWithView:self.view];
    _progressView.labelText = @"玩命加载中";
    [_progressView setMode:MBProgressHUDModeIndeterminate];
    [_progressView show:YES];
    _progressView.backgroundColor = [UIColor colorWithRed:0.73 green:0.76 blue:0.77 alpha:.3];
    [self.view addSubview:_progressView];
    [_progressView release];

}
#pragma mark collectionview cell的样式
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_collectionView == collectionView) {
        PlaceCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath];
        if (_dataArray.count != 0) {
            RecommendData *data = _dataArray[indexPath.section][indexPath.row];
            cell.data = data;
        }
        cell.backgroundColor = [Model shareInstance].BackgroundColor;
        return cell;

    }
    else{
        if (indexPath.section == 0) {
            SearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier1" forIndexPath:indexPath];
            if (_searchArray.count != 0) {
                cell.label.text = [_searchArray[0][indexPath.row] name];
            }
            return cell;
        }
        SearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"identifier1" forIndexPath:indexPath];
        if (_searchArray.count != 0) {
            cell.label.text = [_searchArray[1][indexPath.row] name];
        }
        return cell;
    }
}
#pragma mark collectionview item 个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (_collectionView == collectionView) {
        return [_dataArray[section] count];
    }
    else {
        if (section == 0) {
            return [_searchArray[0] count];
        }
        return [_searchArray[1] count];
    }
}
#pragma mark section 的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    if (_collectionView == collectionView) {
        return _dataArray.count;
    }
    return _searchArr.count;
}

#pragma mark 设置补充视图(页眉或页脚)尺寸
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    if (_collectionView == collectionView) {
        CGSize size = {self.view.frame.size.width, 50 * H};
        return size;
    }
    else {
        CGSize size = {320 * W, 50 * H};
        return size;
    }
}
#pragma mark 为collection view添加一个补充视图(页眉或页脚)
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if (_collectionView == collectionView) {
        TitleCollectionReusableView *headView = [[TitleCollectionReusableView alloc]init];
        headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        headView.titleLabel.text = [NSString stringWithFormat:@"%@", _titleArray[indexPath.section]];
        headView.titleLabel.textColor = [UIColor colorWithRed:0.56 green:0.53 blue:0.93 alpha:1];
        headView.iconImageView.image = [UIImage imageNamed:@"ee"];
        return headView;
    }
    else {
        TitleCollectionReusableView *headView = [[TitleCollectionReusableView alloc]init];
        headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"head" forIndexPath:indexPath];
        headView.titleLabel.text = [NSString stringWithFormat:@"%@", _searchArr[indexPath.section]];
        headView.titleLabel.textColor = [UIColor purpleColor];
        headView.iconImageView.image = [UIImage imageNamed:@"ee"];
        return headView;
    }
}
#pragma mark collectionview点击方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (_collectionView == collectionView) {
        if (indexPath.section == 0) {
            RecommendViewController *recVC = [[RecommendViewController alloc]init];
            if (_dataArray.count != 0) {
                recVC.data = _dataArray[indexPath.section][indexPath.row];
            }
            [self.navigationController pushViewController:recVC animated:YES];
        }
        else{
            OtherViewController *otherVC = [[OtherViewController alloc]init];
            if (_dataArray.count != 0) {
                otherVC.data = _dataArray[indexPath.section][indexPath.row];
            }
            [self.navigationController pushViewController:otherVC animated:YES];
        }
    }
    else{
        OtherViewController *otherVC = [[OtherViewController alloc]init];
        if (_searchArray.count != 0) {
            otherVC.data = _searchArray[indexPath.section][indexPath.row];
        }
        [self.navigationController pushViewController:otherVC animated:YES];
    }
}

#pragma mark searchBar 点击推出界面
-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    if(_flag == 1){
        [UIView animateWithDuration:.5 animations:^{
            _searchView.frame = CGRectMake(0, - self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height);
        }];
        _flag = 0;
    }else
    {
        [UIView animateWithDuration:.5 animations:^{
            _searchView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
            [_cancelButton setHidden:NO];
            
        }];
        _flag = 1;
    }
}
#pragma mark searchBar 回收界面
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    if(_flag == 0){
        [UIView animateWithDuration:.5 animations:^{
            _searchView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
        }];
        _flag = 1;
    }else
    {
        [UIView animateWithDuration:.5 animations:^{
            _searchView.frame = CGRectMake(0, - self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height);
            [_cancelButton setHidden:YES];
        }];
        _flag = 0;
    }
}
#pragma mark cancelButton 点击方法
-(void)cancelButtonAction
{
    [_searchBar resignFirstResponder];
}
-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    self.urlString = searchText;
}
#pragma mark searchButton 点击方法
-(void)searchButtonAction
{
    
    SearchViewController *searchVC = [[SearchViewController alloc]init];
    searchVC.urlString = _urlString;
    [self.navigationController pushViewController:searchVC animated:YES];
    [_searchBar resignFirstResponder];
}

#pragma mark 键盘搜索按钮
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    SearchViewController *searchVC = [[SearchViewController alloc]init];
    searchVC.urlString = _urlString;
    [self.navigationController pushViewController:searchVC animated:YES];
    [_searchBar resignFirstResponder];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [UIView animateWithDuration:.5 animations:^{
        _searchView.frame = CGRectMake(0, - self.view.frame.size.height, self.view.frame.size.width, self.view.frame.size.height);
        [_cancelButton setHidden:YES];
    }];
    [_searchBar resignFirstResponder];
}













- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
